import os
import sys
import json
import sqlite3
import platform
import winreg
import shutil
from subprocess import Popen, PIPE
import ctypes  # 新增导入
import win32api  # 新增导入

def get_chrome_version():
    """获取谷歌浏览器版本"""
    try:
        reg_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path) as key:
            path = winreg.QueryValue(key, None)
            # 获取文件版本信息
            info = win32api.GetFileVersionInfo(path, "\\")
            version = "%d.%d.%d.%d" % (info['FileVersionMS'] / 65536,
                                      info['FileVersionMS'] % 65536,
                                      info['FileVersionLS'] / 65536,
                                      info['FileVersionLS'] % 65536)
            return version
    except Exception as e:
        return "未找到Chrome安装信息"

def disable_features(profile_path):
    """禁用所有相关功能"""
    prefs_path = os.path.join(profile_path, 'Preferences')
    try:
        # 修改浏览器本地配置
        with open(prefs_path, 'r+', encoding='utf-8') as f:
            prefs = json.load(f)
            # 用户配置文件强制设置
            prefs.update({
                'credentials_enable_service': False,
                'password_manager_enabled': False,
                'profile': {'force_disabled': True}  # 阻止用户修改
            })
            f.seek(0)
            json.dump(prefs, f, indent=4)
            f.truncate()
        
        # 设置注册表组策略（需管理员权限）
        reg_path = r"SOFTWARE\Policies\Google\Chrome"
        with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, reg_path) as key:
            # 注册表策略设置
            winreg.SetValueEx(key, "PasswordManagerEnabled", 0, winreg.REG_DWORD, 0)
            winreg.SetValueEx(key, "AutofillCreditCardEnabled", 0, winreg.REG_DWORD, 0)
            winreg.SetValueEx(key, "AutofillAddressEnabled", 0, winreg.REG_DWORD, 0)
            # 新增以下策略增强兼容性
            winreg.SetValueEx(key, "PasswordProtectionWarningTrigger", 0, winreg.REG_DWORD, 2)
            winreg.SetValueEx(key, "SafeBrowsingProtectionLevel", 0, winreg.REG_DWORD, 0)
            
            # 新增策略锁定保护
            winreg.SetValueEx(key, "SettingsUpdatePolicy", 0, winreg.REG_DWORD, 2)  # 禁止策略更新
            winreg.SetValueEx(key, "ExtensionAllowedTypes", 0, winreg.REG_SZ, "")   # 禁止扩展修改
            
        return True
    except Exception as e:
        print(f"设置失败: {str(e)}")
        return False

def check_autofill_status(profile_path):
    """检查所有相关功能状态（补充缺失的函数）"""
    prefs_path = os.path.join(profile_path, 'Preferences')
    try:
        with open(prefs_path, 'r', encoding='utf-8') as f:
            prefs = json.load(f)
            return {
                'autofill': prefs.get('autofill', {}).get('profile_enabled', True),
                'passwords': prefs.get('credentials_enable_service', True),
                'autologin': prefs.get('enable_autologin', True)
            }
    except Exception as e:
        return {'autofill': False, 'passwords': False, 'autologin': False}

def clear_autofill_data(profile_path):
    """清理自动填充记录（补充缺失的函数）"""
    web_data = os.path.join(profile_path, 'Web Data')
    try:
        for process in ['chrome.exe', 'chrome_proxy.exe']:
            Popen(['taskkill', '/F', '/IM', process], shell=True, stdout=PIPE, stderr=PIPE)
            
        conn = sqlite3.connect(web_data)
        c = conn.cursor()
        # 表存在性检查和删除操作
        for table in ['autofill', 'autofill_profile_emails', 'autofill_profiles']:
            c.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
            if c.fetchone():
                c.execute(f"DELETE FROM {table}")
        conn.commit()  # 先提交删除操作
        
        c.execute("VACUUM")  # 在新事务中执行
        conn.commit()  # 提交VACUUM
        
        conn.close()
        return True
    except Exception as e:
        print(f"自动填充清理失败: {str(e)}")
        return False

def clear_password_data(profile_path):
    """清理密码记录"""
    login_data = os.path.join(profile_path, 'Login Data')
    try:
        conn = sqlite3.connect(login_data)
        c = conn.cursor()
        # 修复表存在性检查
        for table in ['logins', 'passwords']:
            c.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
            if c.fetchone():
                # 清除已存储的密码
                c.execute("DELETE FROM logins WHERE ...")
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"密码清理失败: {str(e)}")
        return False

def main():
    # 系统信息
    print(f"操作系统版本: {platform.platform()}")
    print(f"Chrome版本: {get_chrome_version()}")
    
    # 查找用户配置文件（增加Default配置）
    user_data = os.path.join(os.environ['LOCALAPPDATA'], 'Google', 'Chrome', 'User Data')
    profiles = [d for d in os.listdir(user_data) if d.startswith('Profile') or d == 'Default']
    
    for profile in profiles:
        profile_path = os.path.join(user_data, profile)
        print(f"\n检查配置文件: {profile}")
        
        # 检查状态
        status = check_autofill_status(profile_path)
        print(f"自动填充状态: {'启用' if status['autofill'] else '禁用'}")
        print(f"密码保存功能: {'启用' if status['passwords'] else '禁用'}")
        print(f"自动登录功能: {'启用' if status['autologin'] else '禁用'}")

        # 清理所有记录
        print("清理自动填充记录...")
        clear_autofill_data(profile_path)
        print("清理密码记录...")
        clear_password_data(profile_path)
        
        # 禁用所有功能
        print("禁用相关功能...")
        disable_features(profile_path)
        
        # 新增最终验证（重要）
        print("\n最终状态验证:")
        final_status = check_autofill_status(profile_path)
        
        # 验证功能禁用状态
        print(f"密码保存功能状态: {'❌ 仍可启用' if final_status['passwords'] else '✅ 已禁用'}")
        print(f"自动填充状态: {'❌ 仍可启用' if final_status['autofill'] else '✅ 已禁用'}")
        
        # 验证数据库记录清除
        verify_cleanup(profile_path)

def verify_cleanup(profile_path):
    """验证清理结果"""
    try:
        # 检查自动填充数据库
        web_data = os.path.join(profile_path, 'Web Data')
        conn = sqlite3.connect(web_data)
        c = conn.cursor()
        tables = ['autofill', 'autofill_profile_emails', 'autofill_profiles']
        for table in tables:
            # 先检查表是否存在
            c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
            if c.fetchone():
                c.execute(f"SELECT count(*) FROM {table}")
                count = c.fetchone()[0]
                status = '✅ 已清空' if count == 0 else '❌ 清理失败'
            else:
                count = 0
                status = '⚠️ 表不存在'
            print(f"{table}表剩余记录: {count} 条 {status}")
        conn.close()
        
        # 检查密码数据库
        login_data = os.path.join(profile_path, 'Login Data') 
        conn = sqlite3.connect(login_data)
        c = conn.cursor()
        for table in ['logins', 'passwords']:
            c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
            if c.fetchone():
                c.execute(f"SELECT count(*) FROM {table}")
                count = c.fetchone()[0]
                status = '✅ 已清空' if count == 0 else '❌ 清理失败'
            else:
                count = 0
                status = '⚠️ 表不存在'
            print(f"{table}表剩余记录: {count} 条 {status}")
        conn.close()
        
    except Exception as e:
        print(f"验证失败: {str(e)}")

if __name__ == "__main__":
    if sys.platform != 'win32':
        print("本程序仅支持Windows系统")
        sys.exit(1)
        
    try:
        # 自动请求管理员权限
        if not ctypes.windll.shell32.IsUserAnAdmin():
            ctypes.windll.shell32.ShellExecuteW(
                None, "runas", sys.executable, __file__, None, 1
            )
            sys.exit(0)
        main()
    except Exception as e:
        print(f"权限获取失败: {str(e)}")